package com.ddsso.auth.web.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ddsso.auth.web.exception.DistributedSessionException;
import com.ddsso.auth.web.session.DistributedSessionManager;
import com.ddsso.auth.web.session.DistributedSessionRequest;
/**
 * @author zdd
 * @package com.ddsso.auth.web.filter
 * @Time Created by zdd on 2016/11/2.
 * @description  分布式会话过滤器
 * <p>
 * 过滤器必须设置在所有需要使用会话的过滤器之前
 */
public class DistributedSessionFilter extends BaseFilter {

    private static final Logger logger = LoggerFactory.getLogger(DistributedSessionFilter.class);

    private DistributedSessionManager distributedSessionManager;

    /**
     * (non-Javadoc)
     *
     * @see org.springframework.web.filter.OncePerRequestFilter#doFilterInternal(javax.servlet.http.HttpServletRequest,
     *      javax.servlet.http.HttpServletResponse, javax.servlet.FilterChain)
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        DistributedSessionRequest sessionRequest = new DistributedSessionRequest(request, response);
        sessionRequest.setDistributedSessionManager(distributedSessionManager);

        try {
            filterChain.doFilter(sessionRequest, response);
        } finally {
            try {
                sessionRequest.commitSession();
            } catch (DistributedSessionException e) {
                logger.error("fail to commit", e);
            }
        }
    }

    public void setDistributedSessionManager(
            DistributedSessionManager distributedSessionManager) {
        this.distributedSessionManager = distributedSessionManager;
    }

}
